package com.llh.demo4tree.service

import com.llh.demo4tree.entity.NodeAddVO
import com.llh.demo4tree.model.TreeNode
import com.llh.demo4tree.model.TreeNodes
import com.llh.demo4tree.util.NodePathUtil
import org.junit.jupiter.api.Test
import org.ktorm.database.Database
import org.ktorm.dsl.*
import org.ktorm.entity.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import java.time.LocalDateTime

/**
 * 树形数据初始化方法
 * Created At 2021/8/3 17:36
 * @author llh
 */
@SpringBootTest
internal class TreeNodeDataInit {

    @Autowired
    private lateinit var database: Database

    /**
     * 初始化数据。
     * 生成一千条三个层次的数据
     */
//    @Test
    fun initData() {

        database.batchInsert(TreeNodes) {
            for (x in 1..1000) {
                item {
                    set(it.name, "name-$x")
                    set(it.createTime, LocalDateTime.now())
                }
            }
        }

        val all = database.sequenceOf(TreeNodes).sortedBy { it.id }.toList()

        val rootNodes = all.subList(0, 10)

        val first = all.subList(11, 100)
        first.forEach {
            val x = (rootNodes.indices).random()
            it.nodePath = NodePathUtil.contact(rootNodes[x].nodePath, rootNodes[x].id)
            it.pId = rootNodes[x].id
        }

        val second = all.subList(101, 500)

        second.forEach {
            val x = (first.indices).random()
            it.nodePath = NodePathUtil.contact(first[x].nodePath, first[x].id)
            it.pId = first[x].id
        }

        val three = all.subList(501, all.size - 1)
        three.forEach {
            val x = (second.indices).random()
            it.nodePath = NodePathUtil.contact(second[x].nodePath, second[x].id)
            it.pId = second[x].id
        }

        database.batchUpdate(TreeNodes) {
            all.forEach { ele ->
                item {
                    set(it.pId, ele.pId)
                    set(it.nodePath, ele.nodePath)
                    where { it.id eq ele.id }
                }
            }
        }


    }

}